<template>
    <div class="app-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="left">
                <el-button link @click="goBack">
                    <el-icon><ArrowLeft /></el-icon>
                    <span>返回</span>
                </el-button>
                <span class="title">新增商品</span>
            </div>
        </div>

        <!-- 步骤条 -->
        <div class="step-container">
            <el-steps :active="activeStep" finish-status="success">
                <el-step title="基本信息" description="填写商品基本信息">
                    <template #icon>
                        <el-icon><Document /></el-icon>
                    </template>
                </el-step>
                <el-step title="规格设置" description="设置商品规格">
                    <template #icon>
                        <el-icon><SetUp /></el-icon>
                    </template>
                </el-step>
                <el-step title="SKU管理" description="管理商品SKU">
                    <template #icon>
                        <el-icon><Goods /></el-icon>
                    </template>
                </el-step>
            </el-steps>
        </div>

        <!-- 表单内容区域 -->
        <div class="main-content">
            <!-- 步骤一：基本信息 -->
            <div v-show="activeStep === 0" class="step-content">
                <el-form
                    ref="basicFormRef"
                    :model="basicForm"
                    :rules="basicRules"
                    label-width="120px"
                    class="basic-form"
                >
                    <div class="form-card">
                        <div class="card-header">
                            <span class="card-title">基本信息</span>
                        </div>
                        <div class="card-body">
                            <el-row :gutter="24">
                                <el-col :span="12">
                                    <el-form-item label="商品名称" prop="productsName">
                                        <el-input 
                                            v-model="basicForm.productsName" 
                                            placeholder="请输入商品名称"
                                            clearable
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="商品分类" prop="categoryId">
                                        <el-cascader
                                            v-model="basicForm.categoryId"
                                            :options="categoryOptions"
                                            :props="{
                                                checkStrictly: true,
                                                label: 'name',
                                                value: 'id',
                                                emitPath: false
                                            }"
                                            placeholder="请选择商品分类"
                                            clearable
                                            class="w-full"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="24">
                                <el-col :span="12">
                                    <el-form-item label="商品状态" prop="status">
                                        <el-select v-model="basicForm.status" placeholder="请选择商品状态" class="w-full">
                                            <el-option 
                                                v-for="dict in product_status"
                                                :key="dict.value"
                                                :label="dict.label"
                                                :value="dict.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="存储条件" prop="storageCondition">
                                        <el-select v-model="basicForm.storageCondition" placeholder="请选择存储条件" class="w-full">
                                            <el-option 
                                                v-for="dict in product_storage_condition"
                                                :key="dict.value"
                                                :label="dict.label"
                                                :value="dict.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="24">
                                <el-col :span="12">
                                    <el-form-item label="保质期(天)" prop="shelfLife">
                                        <el-input-number 
                                            v-model="basicForm.shelfLife" 
                                            :min="1" 
                                            class="w-full"
                                            controls-position="right"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="产地" prop="origin">
                                        <el-cascader
                                            v-model="basicForm.origin"
                                            :options="regionOptions"
                                            :props="{
                                                expandTrigger: 'hover',
                                                label: 'areaName',
                                                value: 'areaId',
                                                children: 'children'
                                            }"
                                            placeholder="请选择产地"
                                            class="w-full"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="card-header">
                            <span class="card-title">商品描述</span>
                        </div>
                        <div class="card-body">
                            <el-form-item label="商品描述" prop="description">
                                <el-input
                                    v-model="basicForm.description"
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入商品描述"
                                    resize="none"
                                />
                            </el-form-item>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="card-header">
                            <span class="card-title">商品图片</span>
                        </div>
                        <div class="card-body">
                            <el-form-item label="商品主图" prop="mainImage">
                                <div class="image-upload-container">
                                    <el-upload
                                        class="product-uploader"
                                        :action="uploadUrl"
                                        :headers="headers"
                                        :show-file-list="false"
                                        :before-upload="beforeImageUpload"
                                        :on-success="(res) => handleImageSuccess(res, 'mainImage')"
                                    >
                                        <div class="upload-content">
                                            <img v-if="basicForm.mainImage" :src="basicForm.mainImage" class="uploaded-image" />
                                            <div v-else class="upload-placeholder">
                                                <el-icon><Plus /></el-icon>
                                                <div class="upload-text">点击上传主图</div>
                                            </div>
                                        </div>
                                    </el-upload>
                                    <div class="upload-tip">建议尺寸：800x800px，支持jpg、png格式</div>
                                </div>
                            </el-form-item>

                            <el-form-item label="商品图集">
                                <div class="image-upload-container">
                                    <el-upload
                                        class="product-uploader-list"
                                        :action="uploadUrl"
                                        :headers="headers"
                                        list-type="picture-card"
                                        :file-list="basicForm.images"
                                        :before-upload="beforeImageUpload"
                                        :on-success="(res) => handleImageSuccess(res, 'images')"
                                        :on-remove="handleRemove"
                                        multiple
                                        :limit="5"
                                    >
                                        <el-icon><Plus /></el-icon>
                                    </el-upload>
                                    <div class="upload-tip">最多上传5张商品展示图片</div>
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
            </div>

            <!-- 步骤二：规格设置 -->
            <div v-show="activeStep === 1" class="step-content">
                <div class="form-card">
                    <div class="card-header">
                        <span class="card-title">规格设置</span>
                    </div>
                    <div class="card-body">
                        <div class="spec-container">
                            <div class="spec-list">
                                <el-empty v-if="specForm.specifications.length === 0" description="暂无规格信息">
                                    <el-button type="primary" @click="addSpec">添加规格</el-button>
                                </el-empty>
                                <template v-else>
                                    <div v-for="(spec, index) in specForm.specifications" :key="index" class="spec-item">
                                        <div class="spec-header">
                                            <span class="spec-index">规格{{ index + 1 }}</span>
                                            <el-button 
                                                type="danger" 
                                                :icon="Delete" 
                                                circle 
                                                @click="removeSpec(index)"
                                            />
                                        </div>
                                        <el-row :gutter="24">
                                            <el-col :span="8">
                                                <el-form-item :label="'规格名称'" :prop="'specifications.' + index + '.name'">
                                                    <el-input 
                                                        v-model="spec.name" 
                                                        placeholder="请输入规格名称，如：重量"
                                                        clearable 
                                                    />
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="16">
                                                <el-form-item :label="'规格值'" :prop="'specifications.' + index + '.values'">
                                                    <el-select
                                                        v-model="spec.values"
                                                        multiple
                                                        filterable
                                                        allow-create
                                                        default-first-option
                                                        placeholder="请输入规格值，如：1斤、3斤"
                                                        class="w-full"
                                                    >
                                                    </el-select>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </div>
                                    <div class="spec-actions">
                                        <el-button type="primary" @click="addSpec" :icon="Plus">添加规格</el-button>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 步骤三：SKU管理 -->
            <div v-show="activeStep === 2" class="step-content">
                <div class="form-card">
                    <div class="card-header">
                        <span class="card-title">SKU管理</span>
                        <div class="card-extra">
                            <el-button type="primary" @click="batchSetPrice" :icon="Money">批量设置价格</el-button>
                            <el-button type="primary" @click="batchSetStock" :icon="Box">批量设置库存</el-button>
                        </div>
                    </div>
                    <div class="card-body">
                        <el-table 
                            :data="skuForm.skuList" 
                            border 
                            class="sku-table"
                            :header-cell-style="{ background: '#f5f7fa' }"
                        >
                            <el-table-column label="规格组合" min-width="200">
                                <template #default="scope">
                                    <div class="sku-specs">
                                        <el-tag
                                            v-for="(spec, index) in scope.row.specs"
                                            :key="index"
                                            size="small"
                                            class="mx-1"
                                            effect="plain"
                                        >
                                            {{ spec.name }}: {{ spec.value }}
                                        </el-tag>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="价格" width="200">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.price"
                                        :precision="2"
                                        :step="0.1"
                                        :min="0"
                                        controls-position="right"
                                        class="w-full"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="库存" width="200">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.stock"
                                        :min="0"
                                        controls-position="right"
                                        class="w-full"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column label="图片" width="120">
                                <template #default="scope">
                                    <el-upload
                                        class="sku-image-uploader"
                                        :action="uploadUrl"
                                        :headers="headers"
                                        :show-file-list="false"
                                        :before-upload="beforeImageUpload"
                                        :on-success="(res) => handleSkuImageSuccess(res, scope.$index)"
                                    >
                                        <img
                                            v-if="scope.row.image"
                                            :src="scope.row.image"
                                            class="sku-image"
                                        />
                                        <el-icon v-else class="upload-icon"><Plus /></el-icon>
                                    </el-upload>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>

            <!-- 底部操作按钮 -->
            <div class="footer-buttons">
                <el-button 
                    @click="handlePrev" 
                    v-if="activeStep > 0"
                    :icon="ArrowLeft"
                >
                    上一步
                </el-button>
                <el-button 
                    type="primary" 
                    @click="handleNext" 
                    v-if="activeStep < 2"
                    :icon="ArrowRight"
                >
                    下一步
                </el-button>
                <el-button 
                    type="success" 
                    @click="handleSubmit" 
                    v-if="activeStep === 2"
                    :icon="Check"
                >
                    提交
                </el-button>
            </div>
        </div>

        <!-- 批量设置价格弹窗 -->
        <el-dialog
            v-model="batchPriceDialog"
            title="批量设置价格"
            width="400px"
            destroy-on-close
            center
        >
            <el-form :model="batchPriceForm" label-width="80px">
                <el-form-item label="价格">
                    <el-input-number
                        v-model="batchPriceForm.price"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        controls-position="right"
                        class="w-full"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchPriceDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmBatchPrice">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 批量设置库存弹窗 -->
        <el-dialog
            v-model="batchStockDialog"
            title="批量设置库存"
            width="400px"
            destroy-on-close
            center
        >
            <el-form :model="batchStockForm" label-width="80px">
                <el-form-item label="库存">
                    <el-input-number
                        v-model="batchStockForm.stock"
                        :min="0"
                        controls-position="right"
                        class="w-full"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchStockDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmBatchStock">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance,onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { getToken } from '@/utils/auth';
import { useDict } from '@/utils/dict';
import { listCategoriesCli } from '@/api/farmer/categories';
import { getSystemArea } from '@/api/system/common.js';
import { addProducts } from '@/api/farmer/products';
import { 
    Plus, 
    Delete, 
    Document, 
    SetUp, 
    Goods,
    ArrowLeft,
    ArrowRight,
    Check,
    Money,
    Box
} from '@element-plus/icons-vue';

const router = useRouter();
const { proxy } = getCurrentInstance();

// 获取字典数据
const { product_storage_condition, product_status } = useDict('product_storage_condition', 'product_status');

// 返回上一页
const goBack = () => {
    router.go(-1);
};

// 上传相关配置
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/common/upload";
const headers = { Authorization: 'Bearer ' + getToken() };

// 当前步骤
const activeStep = ref(0);

// 基本信息表单
const basicForm = reactive({
    productsName: '',
    categoryId: '',
    status: '',
    storageCondition: '',
    shelfLife: 1,
    origin: [],
    description: '',
    mainImage: '',
    images: []
});

// 规格表单
const specForm = reactive({
    specifications: []
});

// SKU表单
const skuForm = reactive({
    skuList: []
});

// 批量设置相关
const batchPriceDialog = ref(false);
const batchStockDialog = ref(false);
const batchPriceForm = reactive({ price: 0 });
const batchStockForm = reactive({ stock: 0 });

// 分类数据
const categoryOptions = ref([]);
// 地区数据
const regionOptions = ref([]);

// 表单验证规则
const basicRules = {
    productsName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' }
    ],
    mainImage: [
        { required: true, message: '请上传商品主图', trigger: 'change' }
    ]
};


onMounted(() => {
    listRegions();
    listCategorys();
});

const listRegions = async () => {
    const res = await getSystemArea()
    regionOptions.value = res.data
}
const listCategorys = async () => {
    const res = await listCategoriesCli()
    categoryOptions.value = res.data
}
// 图片上传前的验证
const beforeImageUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
        return false;
    }
    return true;
};

// 处理图片上传成功
const handleImageSuccess = (res, field) => {
    if (res.code === 200) {
        if (field === 'mainImage') {
            basicForm.mainImage = res.url;
        } else if (field === 'images') {
            if (!basicForm.images) {
                basicForm.images = [];
            }
            basicForm.images.push({ url: res.url });
        }
        ElMessage.success('上传成功');
    } else {
        ElMessage.error('上传失败');
    }
};

// 处理图片移除
const handleRemove = (file) => {
    const index = basicForm.images.findIndex(item => item.url === file.url);
    if (index !== -1) {
        basicForm.images.splice(index, 1);
    }
};

// 添加规格
const addSpec = () => {
    specForm.specifications.push({
        name: '',
        values: []
    });
};

// 移除规格
const removeSpec = (index) => {
    specForm.specifications.splice(index, 1);
    generateSkuList();
};

// 生成SKU列表
const generateSkuList = () => {
    if (specForm.specifications.length === 0) {
        skuForm.skuList = [{
            specs: [],
            price: 0,
            stock: 0,
            image: ''
        }];
        return;
    }

    const specValues = specForm.specifications.map(spec => 
        spec.values.map(value => ({
            name: spec.name,
            value: value
        }))
    );

    // 计算笛卡尔积
    const cartesian = (...arrays) => {
        return arrays.reduce((acc, curr) => {
            return acc.flatMap(x => curr.map(y => [...x, y]));
        }, [[]]);
    };

    const combinations = cartesian(...specValues);
    skuForm.skuList = combinations.map(specs => ({
        specs,
        price: 0,
        stock: 0,
        image: ''
    }));
};

// 处理SKU图片上传成功
const handleSkuImageSuccess = (res, index) => {
    if (res.code === 200) {
        skuForm.skuList[index].image = res.url;
        ElMessage.success('上传成功');
    } else {
        ElMessage.error('上传失败');
    }
};

// 批量设置价格
const batchSetPrice = () => {
    batchPriceDialog.value = true;
};

// 确认批量设置价格
const confirmBatchPrice = () => {
    skuForm.skuList.forEach(sku => {
        sku.price = batchPriceForm.price;
    });
    batchPriceDialog.value = false;
    ElMessage.success('批量设置价格成功');
};

// 批量设置库存
const batchSetStock = () => {
    batchStockDialog.value = true;
};

// 确认批量设置库存
const confirmBatchStock = () => {
    skuForm.skuList.forEach(sku => {
        sku.stock = batchStockForm.stock;
    });
    batchStockDialog.value = false;
    ElMessage.success('批量设置库存成功');
};

// 上一步
const handlePrev = () => {
    if (activeStep.value > 0) {
        activeStep.value--;
    }
};

// 下一步
const handleNext = async () => {
    if (activeStep.value === 0) {
        // 验证基本信息
        try {
            await proxy.$refs.basicFormRef.validate();
            activeStep.value++;
        } catch (error) {
            return;
        }
    } else if (activeStep.value === 1) {
        // 验证规格信息
        if (specForm.specifications.length === 0) {
            ElMessage.warning('请至少添加一个规格');
            return;
        }
        for (const spec of specForm.specifications) {
            if (!spec.name || spec.values.length === 0) {
                ElMessage.warning('请完善规格信息');
                return;
            }
        }
        generateSkuList();
        activeStep.value++;
    }
};

// 提交表单
const handleSubmit = async () => {
    // 验证SKU信息
    if (skuForm.skuList.length === 0) {
        ElMessage.warning('请至少添加一个SKU');
        return;
    }

    for (const sku of skuForm.skuList) {
        if (sku.price <= 0 || sku.stock <= 0) {
            ElMessage.warning('请完善SKU价格和库存信息');
            return;
        }
    }

    // 组装提交数据
    const submitData = {
        ...basicForm,
        specifications: specForm.specifications,
        skuList: skuForm.skuList
    };

    try {
        // TODO: 调用添加商品接口
        const res = await addProducts(submitData)
        //console.log('提交的数据：', submitData);
        ElMessage.success('添加商品成功');
        router.push('/products/manager');
    } catch (error) {
        ElMessage.error('添加商品失败');
    }
};
</script>

<style lang="scss" scoped>
.app-container {
    background-color: #f5f7fa;
    min-height: calc(100vh - 84px);
    padding: 16px;
}

.page-header {
    height: 56px;
    line-height: 56px;
    background-color: #fff;
    padding: 0 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 4px 4px 0 0;

    .left {
        display: flex;
        align-items: center;
        gap: 16px;

        .title {
            font-size: 16px;
            font-weight: 500;
            color: #1f2f3d;
            color: var(--el-text-color-primary);
        }
    }
}

.step-container {
    background-color: #fff;
    padding: 24px;
    border-top: 1px solid #f0f0f0;
}

.main-content {
    background-color: #fff;
    padding: 24px;
    border-top: 1px solid #f0f0f0;
    border-radius: 0 0 4px 4px;
    
    .step-content {
        animation: fade-in 0.3s ease-in-out;
    }
}

.form-card {
    background-color: #fafafa;
    border-radius: 4px;
    margin-bottom: 16px;

    .card-header {
        height: 48px;
        line-height: 48px;
        padding: 0 16px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .card-title {
            font-size: 14px;
            font-weight: 500;
            color: #1f2f3d;
        }

        .card-extra {
            display: flex;
            gap: 8px;
        }
    }

    .card-body {
        padding: 24px;
    }
}

.spec-container {
    .spec-item {
        background-color: #fff;
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        padding: 16px;
        margin-bottom: 16px;

        .spec-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;

            .spec-index {
                font-size: 14px;
                font-weight: 500;
                color: #1f2f3d;
            }
        }
    }

    .spec-actions {
        text-align: center;
        margin-top: 24px;
    }
}

.footer-buttons {
    margin-top: 24px;
    padding: 24px;
    text-align: center;
    background-color: #fafafa;
    border-radius: 4px;

    .el-button {
        min-width: 120px;
        margin: 0 8px;
    }
}

.w-full {
    width: 100%;
}

.mx-1 {
    margin: 0 4px;
}

@keyframes fade-in {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

// 图片上传相关样式
.image-upload-container {
    .upload-content {
        display: inline-block;
    }
}

.product-uploader {
    .upload-placeholder {
        width: 200px;
        height: 200px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            border-color: var(--el-color-primary);

            .el-icon {
                color: var(--el-color-primary);
            }

            .upload-text {
                color: var(--el-color-primary);
            }
        }

        .el-icon {
            font-size: 28px;
            color: #8c939d;
            transition: all 0.3s;
        }

        .upload-text {
            margin-top: 8px;
            color: #8c939d;
            transition: all 0.3s;
        }
    }

    .uploaded-image {
        width: 200px;
        height: 200px;
        object-fit: cover;
        border-radius: 4px;
    }
}

.upload-tip {
    font-size: 12px;
    color: #8c939d;
    margin-top: 8px;
}

.sku-image-uploader {
    :deep(.el-upload) {
        width: 80px;
        height: 80px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            border-color: var(--el-color-primary);
        }
    }

    .sku-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 4px;
    }

    .upload-icon {
        font-size: 24px;
        color: #8c939d;
        transition: all 0.3s;

        &:hover {
            color: var(--el-color-primary);
        }
    }
}
</style> 